package user

import (
	"github.com/gin-gonic/gin"
	"smartLearn/models"
	"smartLearn/modules/response"
	"smartLearn/public/common"
	"strconv"
)
type RegUser struct {
	Username string `form:"username" json:"username" binding:"required"`
	Password  string `form:"password" json:"password" binding:"required"`
	Salt      string    `json:"salt" xorm:"not null comment('盐') VARCHAR(4)"`
	Realname string `form:"realname" json:"realname" binding:"required"`
	Telphone   string `form:"telphone" json:"telphone" binding:"required"`

	Comment   string `form:"Comment" json:"Comment" binding:"required"`

}

func Create(c *gin.Context)  {
	userModel := models.SystemUser{};
	//读取post上来的信息
	userModel.Username= c.Query("username")
	if userModel.Username=="" {
		response.ShowError(c, "输入参数错误")
		return
	}
	has:=userModel.GetRow()
	if has {
		response.ShowError(c, "用户已经存在")
		return
	}

	userModel.Password=c.Query("password")
	userModel.Realname=c.Query("realname")
	userModel.Password=c.Query("password")
	userModel.Telphone=c.Query("telphone")
	userModel.Comment=c.Query("comment")
	userModel.Salt =common.GetRandomBoth(4)

	userModel.Password = common.Sha1En(userModel.Password+userModel.Salt)
	roleid,err:=strconv.Atoi(c.Query("roleid"))
	//添加角色
	if err!=nil {
		response.ShowError(c,err.Error())
		return
	}

	//用户添加到数据库，同时加上用户角色关系表？

	_,err=userModel.Add(roleid)
	if err!=nil {
		response.ShowError(c,err.Error())
		return
	}

	response.ShowData(c,userModel)
	return
}

func GetRollAll(c *gin.Context)  {
	roleModel := models.SystemRole{};
	roleList:=roleModel.GetAllNames()
	var list = map[string] []models.ClientRoleInfo{
		"list":roleList,
	}


	response.ShowData(c,list)
	return
}

func IsExist(c *gin.Context)  {
	userModel := models.SystemUser{};
	username,bExist:=c.GetQuery("username")

	if bExist==false {
		response.ShowError(c,"输入参数错误")
	}

	userModel.Username=username

	has :=userModel.GetRow()
	var rMap = map[string] int{
		"exist":0,
	}

	if has{
		rMap["exist"]=1

	}
	response.ShowData(c,rMap)

	return
}

